<?php

class CustStockOutHead extends AppModel {

    var $name = 'CustStockOutHead';
    var $useTable = 'cust_stock_out_heads';
    var $displayField = 'stock_out_no';
    var $hasMany = array(
        'CustStockOut' => array(
            'foreignKey' => 'cust_stock_out_head_id'
        )
    );
    var $belongsTo = array(
        'Supplier', 'SiteCostCenter', 'SiteUser', 'CustStockOutType',
        'CustReserveHead' => array(
            'fields' => array('id', 'reserve_no')
        ),
        'Customer' => array(
            'fields' => array('id', 'cust_no', 'name')
        ),
        'Site' => array(
            'fields' => array('id', 'site_no', 'name', 'have_cost_center')
        ),
        'User' => array(
            'foreignKey' => 'collector_id',
            'fields' => array('username', 'name')
        )
    );
    var $validate = array(
        'stock_out_no' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'Stock in no is required.',
                'required' => true,
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'This Stock in no is already taken.',
                'on' => 'create'
            ),
        ),
        'stock_out_date' => array(
            'rule' => array('date', 'dmy'),
            'message' => 'Stock out date is required.',
            'required' => true,
        ),
        'dispatch_from' => array(
            'rule' => 'notEmpty',
            'message' => 'Dispatch from required.',
            'required' => true,
        ),
        'customer_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Customer is required.',
            'required' => true,
        ),
        'cust_stock_out_type_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Stock out type required.',
            'required' => true,
        ),
        'site_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Site is required.',
            'required' => true,
        ),
    );

    function beforeSave() {
        if (isset($this->data['CustStockOutHead']['stock_out_date'])) {
            $this->data['CustStockOutHead']['stock_out_date'] = $this->dateFormatBeforeSave($this->data['CustStockOutHead']['stock_out_date']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$custStockOutHead) {
            if (isset($custStockOutHead['CustStockOutHead']['stock_out_date'])) {
                $custStockOutHead['CustStockOutHead']['stock_out_date'] = $this->dateFormatAfterFind($custStockOutHead['CustStockOutHead']['stock_out_date']);
            }
            if (isset($custStockOutHead['CustStockOutHead']['stock_out_time'])) {
                $custStockOutHead['CustStockOutHead']['stock_out_time'] = $this->dateTimeFormatAfterFind($custStockOutHead['CustStockOutHead']['stock_out_time'], false);
            }
        }
        return $results;
    }

    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int $id cust_stock_out_head_id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'Supplier', 'SiteCostCenter', 'SiteUser', 'CustReserveHead',
            'CustStockOut' => array('Product' => array('part_no', 'supplier_part_no', 'text', 'Unit'), 'CustProductSite')
                )
        );
        $data = $this->findById($id);

        $this->CustStockOut->bindModel(array(
            'hasMany' => array(
                'ProductSerial' => array(
                    'foreignKey' => 'cust_stock_out_id',
                    'conditions' => array(
                        'cust_stock_out_type' => CustStockOut::STOCK_OUT_TYPE
                    )
                )
            )
                )
        );

        $Product = $this->CustStockOut->Product;
        $PS = $this->CustStockOut->ProductSerial;
        $CL = $PS->CustLocation;

        // วนลูปรายการ CustStockOut
        foreach ($data['CustStockOut'] as &$cso) {
            // หา Location ที่มีอยู่ใน CustStockOut รายการนี้
            $psCLs = $PS->find('all', array(
                        'fields' => array('DISTINCT cust_location_id', 'cust_stock_out_price'),
                        'conditions' => array(
                            'cust_stock_out_id' => $cso['id'],
                            'cust_stock_out_type' => CustStockOut::STOCK_OUT_TYPE,
                            'product_id' => $cso['product_id'],
//                            'is_active_flag' => true
                        ),
                        'contain' => array()
                            )
            );

            // แปะ Location ที่ได้เข้า CustStockOut
            foreach ($psCLs as $psCl) {
                $CL->contain();
                $custLocation = $CL->findById($psCl['ProductSerial']['cust_location_id']);

                // option สำหรับ query product serial
                $options = array(
                    'contain' => array(),
                    'conditions' => array(
                        'cust_stock_out_id' => $cso['id'],
                        'cust_stock_out_type' => CustStockOut::STOCK_OUT_TYPE,
                        'product_id' => $cso['product_id'],
                        'cust_location_id' => $psCl['ProductSerial']['cust_location_id'],
                        'cust_stock_out_price' => $psCl['ProductSerial']['cust_stock_out_price'],
                    )
                );

                // นับจำนวนที่ stock out ทั้งหมด ใน location นี้
                $stock_out_qty = $PS->find('count', $options);

                // นับจำนวนที่ return
                $options['conditions']['is_active_flag'] = false;
                $return_qty = $PS->find('count', $options);

                // นับจำนวนที่ stock out ออกไปจริง
                $options['conditions']['is_active_flag'] = true;
                $net_stock_out_qty = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

//                                'is_active_flag' => true    // เอาเฉพาะที่ active (ไม่มีการ return)
                $custLocation['cust_stock_out_price'] = $psCl['ProductSerial']['cust_stock_out_price'];
                $custLocation['stock_out_qty'] = $stock_out_qty;
                $custLocation['return_qty'] = $return_qty;
                $custLocation['net_stock_out_qty'] = $net_stock_out_qty;
                $custLocation['PS'] = $ps;

                $cso['ProductLocation'][] = $custLocation;
            }
        }
        return $data;
    }

}

?>
